library(plyr)
library(stringr)
library(magrittr)
library(tidyverse)


rm(list=ls())
home = 'C:/Users/Jason/Dropbox/VNA_Responsiveness/Analysis/JOP-dataverse/'


permutation.results = paste0(home, 'RI-analyses.Rds') %>%
  readRDS
experimental.results = paste0(home, 'experimental-analyses.Rds') %>%
  readRDS


Random = subset(permutation.results, 
                Result %in% c('tab3col4x','tab3col5x','tab3col6x') & 
                  !term %in% c('FullTime','CentNom','Competitive'))
Actual = ddply(.data=Random, 
               .variables=c('Result','term'), 
               .fun=function(Coefficient) {
  X = Coefficient$estimate
  qest = ecdf(X)
  Y = subset(experimental.results, 
             Result==Coefficient$Result[1] & term==Coefficient$term[1])$estimate
  Q = mapvalues(x=as.integer(round(1000*qest(Y))), 
                from=seq(0L, 1000L, 1L),
                to=paste0('(', 
                          str_pad(string=c(seq(from=0L, 
                                               to=499L, 
                                               by=1L)/500L, 
                                           0.500, 
                                           seq(from=499L, 
                                               to=0L, 
                                               by=-1L)/500L), 
                                  width=5, 
                                  side='right', 
                                  pad=0), 
                          ')'),
                warn_missing=F)
  data.frame(estimate=Y, 
             Significance=Q, 
             stringsAsFactors=F)
}, .inform=T) %>%
  mutate(Term=mapvalues(x=term, 
                        from=c('Citizen',
                               'Firm',
                               '(Intercept)'),
                        to=3:1,
                        warn_missing=F),
         Term=as.integer(Term),
         Result=mapvalues(x=Result,
                          from=c('tab3col4x',
                                 'tab3col5x',
                                 'tab3col6x'),
                          to=c('1) Floor debate; All delegates\nn = 470',
                               '2) Query session; All delegates\nn = 470',
                               '3) Group caucus; All delegates\nn = 470'), 
                          warn_missing=F),
         Result=factor(x=Result,
                       levels=c('1) Floor debate; All delegates\nn = 470',
                                '2) Query session; All delegates\nn = 470',
                                '3) Group caucus; All delegates\nn = 470')))
Random = Random %>%
  mutate(Term=mapvalues(x=term, 
                        from=c('Citizen',
                               'Firm',
                               '(Intercept)'),
                        to=3:1,
                        warn_missing=F),
         Term=as.integer(Term),
         Result=mapvalues(x=Result,
                                 from=c('tab3col4x',
                                        'tab3col5x',
                                        'tab3col6x'),
                                 to=c('1) Floor debate; All delegates\nn = 470',
                                      '2) Query session; All delegates\nn = 470',
                                      '3) Group caucus; All delegates\nn = 470'), 
                                 warn_missing=F),
         Result=factor(x=Result,
                       levels=c('1) Floor debate; All delegates\nn = 470',
                                '2) Query session; All delegates\nn = 470',
                                '3) Group caucus; All delegates\nn = 470')))
Bounds = (max(abs(c(Actual$estimate, Random$estimate)))+0.1)
xLabels = seq(from=(-1)*max(floor(Bounds), 1), 
              to=max(floor(Bounds), 1), 
              by=1L)
Effects = paste(str_pad(string=str_extract(string=Actual$estimate, 
                                           pattern='.*(?=\\.)'), 
                        width=2, 
                        side='left', 
                        pad=' '),
                str_pad(string=str_extract(string=round(Actual$estimate, digits=3), 
                                           pattern='(?<=\\.).*'), 
                        width=3, 
                        side='right', 
                        pad='0'), 
                sep='.') %>%
  as.data.frame(stringsAsFactors=F) %>%
  set_colnames('Label') %>%
  mutate(estimate=xLabels[1]+0.05, 
         Term=Actual$Term, 
         Result=Actual$Result,
         Significance=Actual$Significance,
         Label=str_c(Label, '\n', Significance))
tmp = subset(Random, Term==3L) %>%
  ggplot(aes(x=estimate)) +
  geom_density() +
  facet_wrap(~Result, nrow=1)
Citizen = ggplot_build(tmp)$data[[1]] %>%
  mutate(scaled=(scaled*0.8)+3, ymin=ymin+3,
         Result=mapvalues(x=PANEL, 
                          from=1:3, 
                          to=c('1) Floor debate; All delegates\nn = 470',
                               '2) Query session; All delegates\nn = 470',
                               '3) Group caucus; All delegates\nn = 470'), 
                          warn_missing=F))
tmp = subset(Random, Term==2L) %>%
  ggplot(aes(x=estimate)) +
  geom_density() +
  facet_wrap(~Result, nrow=1)
Firm = ggplot_build(tmp)$data[[1]] %>%
  mutate(scaled=(scaled*0.8)+2, ymin=ymin+2,
         Result=mapvalues(x=PANEL, 
                          from=1:3, 
                          to=c('1) Floor debate; All delegates\nn = 470',
                               '2) Query session; All delegates\nn = 470',
                               '3) Group caucus; All delegates\nn = 470'), 
                          warn_missing=F))
tmp = subset(Random, Term==1L) %>%
  ggplot(aes(x=estimate)) +
  geom_density() +
  facet_wrap(~Result, nrow=1)
Constant = ggplot_build(tmp)$data[[1]] %>%
  mutate(scaled=(scaled*0.8)+1, ymin=ymin+1,
         Result=mapvalues(x=PANEL, 
                          from=1:3, 
                          to=c('1) Floor debate; All delegates\nn = 470',
                               '2) Query session; All delegates\nn = 470',
                               '3) Group caucus; All delegates\nn = 470'), 
                          warn_missing=F))
g = ggplot(data=Random, 
           aes(x=estimate, y=Term)) +
  geom_vline(xintercept=0, linetype=2, color='red') +
  geom_point(size=1, alpha=0.01) +
  geom_text(data=Effects, 
            aes(x=estimate, y=Term, label=Label), 
            size=3, alpha=1, color='black', hjust=0, inherit.aes=F) +
  geom_ribbon(data=Citizen, 
              aes(x=x, ymin=ymin, ymax=scaled), 
              fill='black', color='black', alpha=0.25, size=0.25, inherit.aes=F) +
  geom_ribbon(data=Firm, 
              aes(x=x, ymin=ymin, ymax=scaled), 
              fill='black', color='black', alpha=0.25, size=0.25, inherit.aes=F) +
  geom_ribbon(data=Constant, 
              aes(x=x, ymin=ymin, ymax=scaled), 
              fill='black', color='black', alpha=0.25, size=0.25, inherit.aes=F) +
  geom_segment(data=Actual, 
               aes(x=estimate, xend=estimate, y=Term, yend=Term+0.8), 
               size=0.25, alpha=1, linetype=1, inherit.aes=F) +
  geom_point(data=Actual, 
             aes(x=estimate, y=Term), 
             fill='white', size=2, alpha=1, shape=21, inherit.aes=F) +
  scale_x_continuous(breaks=xLabels) +
  scale_y_continuous(breaks=3:1, 
                     labels=c('Citizen',
                              'Firm',
                              'Constant')) +
  labs(x=NULL, y=NULL) +
  guides(fill=guide_legend(override.aes=list(size=3))) +
  coord_cartesian(xlim=range(xLabels), ylim=c(0.7, 4), expand=F) +
  facet_wrap(~Result, nrow=1) +
  theme_minimal() +
  theme(axis.text=element_text(size=8, color='black'),
        strip.text=element_text(size=9),
        legend.title=element_text(size=9),
        legend.text=element_text(size=8),
        legend.position='bottom',
        plot.margin=unit(c(0.1, 0.2, 0.1, 0.1), 'in'),
        panel.spacing.x=unit(0.2, 'in'),
        panel.border=element_rect(color='black', fill=NA))   


ggsave('appendix-figure-13-1.png', g, path=home, width=9, height=3, units='in')
ggsave('appendix-figure-13-1.tiff', g, path=home, width=9, height=3, units='in')
